<?php


namespace app\backend\services;

use App\backend\models\LifeFreeModel;
use App\backend\models\LifeFreeTicketModel;
use App\common\services\BaseServices;
use App\backend\models\LifeFreeLogModel;
use Illuminate\Support\Facades\DB;
use Overtrue\LaravelPinyin\Facades\Pinyin;
use App\backend\services\OpenPrizeServices;

class LifeFreeServices extends BaseServices
{
    const TYPE_ONE = 1;
    const TYPE_TWO = 2;
    //分页条数
    const pageSize = 3;

    /**
     * 获取奖券编码号
     * 活动名称首字母简写+活动创建年月日+xxxxx
     * @param $name
     * @param $num
     * @return string
     */
    public function getTicketCode($name, $num)
    {
        $pinyin = app('pinyin');
        $py_name = $pinyin->abbr($name);
        $py_name = strtoupper(substr($py_name, 0, 5));
        return $py_name . date("Ymd") . sprintf("%06d", $num);
    }

    /**
     * 基础数据--参数验证
     * @param $data
     * @return array
     */
    public static function checkBaseSetParam($data)
    {
        if (empty($data) && $data == false) {
            return self::returnError(40201, '未设置参数');
        }

        //开启部分用户权限--
        if ($data['authority'] == self::TYPE_ONE) {
            if (empty($data['only_member_level'])) {
                $msg = '请设置-限定的（会员等级）';
                return self::returnError(40209, $msg);
            }
            if (empty($data['only_distri_level'])) {
                $msg = '请设置-限定的（分销等级）';
                return self::returnError(40210, $msg);
            }
            if (empty($data['nopermission_tip'])) {
                $msg = '请设置-无权限提示语';
                return self::returnError(40211, $msg);
            }
        } else {
            $data['only_member_level'] = '';
            $data['only_distri_level'] = '';
            $data['nopermission_tip'] = '';
        }
        //处理参数 活动渠道，会员分级，分销等级
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $data['activity_channels'] = self::arrayToString($data['activity_channels']);
        $data['only_member_level'] = self::arrayToString($data['only_member_level']);
        $data['only_distri_level'] = self::arrayToString($data['only_distri_level']);

        return self::returnSuccess('ok', $data);
    }


    /**
     * 奖品设置--参数验证
     * @param $request
     * @return array
     */
    public static function checkPrizeSetParam($request)
    {
        $data = $request;

        //公共参数验证
        $param_res = self::checkBaseParam($data);
        if ($param_res['status'] != 0) {
            return self::returnError($param_res['status'] . $param_res['msg']);
        }

        return self::returnSuccess('ok', $data);
    }

    /**
     * 开奖设置-参数验证
     * @param $data
     * @return array
     */
    public static function checkDrawPrizeSetParam($data)
    {
        if (empty($data) && $data == false) {
            return self::returnError(40201, '未设置参数');
        }

        //公共参数验证
        $param_res = self::checkBaseParam($data);
        if ($param_res['status'] != 0) {
            return self::returnError($param_res['status'] . $param_res['msg']);
        }

        //测试
//        if (!self::paramExist('trigger_by_ticket', $data)) {
//            return self::returnError(40232, '请设置奖券数量');
//        }
        if (isset($data['trigger_by_ticket']) && $data['trigger_by_ticket'] == self::TYPE_ONE) {
            if (empty($data['open_specify_num'])) {
                $msg = '请设置奖券数量';
                return self::returnError(40232, $msg);
            }
        }
        if (isset($data['trigger_by_time']) && $data['trigger_by_time'] == self::TYPE_ONE) {
            if (empty($data['open_specify_time'])) {
                $msg = '请设置指定时间';
                return self::returnError(40233, $msg);
            }
            //获取活动开始时间
            $a_info = self::getActivityById($data['id'], ['start_time']);
            if ($a_info->start_time > $data['open_specify_time']) {
                $msg = '指定时间不能小于活动开始时间';
                return self::returnError(40233, $msg);
            }
        }
        //积分购买奖券
        if (isset($data['is_point_buy']) && $data['is_point_buy'] == self::TYPE_ONE) {
            if (self::paramExist('need_point', $data)) {
                return self::returnError(40234, '购买积分不能为空');
            }
            if (!isset($data['point_max_num'])) {
                return self::returnError(40234, '请设置购买上限');
            }
        }
        //金额购买奖券
        if (isset($data['is_amount_buy']) && $data['is_amount_buy'] == self::TYPE_ONE) {
            if (self::paramExist('need_amount', $data)) {
                return self::returnError(40234, '购买金额不能为空');
            }
            if (!isset($data['amount_max_num'])) {
                return self::returnError(40234, '请设置购买上限');
            }
        }
        //中奖概率
        $data['system_win_chance'] = isset($data['system_win_chance']) ? $data['system_win_chance'] : 0;
        if (bcadd($data['system_win_chance'], $data['user_win_chance']) > 100) {
            $msg = '中奖概率不能大于100';
            return self::returnError(40234, $msg);
        }
        //指定中奖
        if ($data['appoint_win'] == self::TYPE_ONE) {
            if (empty($data['win_user'])) {
                $msg = '请设置指定中奖用户';
                return self::returnError(40235, $msg);
            }
        } elseif ($data['appoint_win'] == self::TYPE_TWO) {
            if (empty($data['win_ticket'])) {
                $msg = '请设置指定中奖券';
                return self::returnError(40236, $msg);
            }
        }

        return self::returnSuccess('ok', $data);
    }

    /**
     * 验证参数--基础参数
     * @param $data
     * @return array
     */
    public function checkBaseParam($data)
    {
        if (empty($data) && $data == false) {
            return self::returnError(40201, '未设置参数！');
        }
        if (!isset($data['id']) || empty($data['id'])) {
            return self::returnError(40202, '参数不能为空！');
        }
        if (!self::activityExists($data['id'])) {
            return self::returnError(40226, '数据不存在');
        }
        return self::returnSuccess('ok', $data);
    }

    /**
     * 数据--保存
     * @param $data
     * @return array|bool|int|string
     */
    public static function modifyActivity($data)
    {
        if (empty($data) && $data == false) {
            return [];
        }

        $id = !empty($data['id']) ? $data['id'] : 0;
        unset($data['id']);

        if ($id) {
            $res = LifeFreeModel::getInstance()->updateSave(['id' => $id], $data);
        } else {
            $res = LifeFreeModel::getInstance()->insertSave($data);
        }
        return $res;
    }

    /**
     * 删除活动
     * @param $data
     * @return array
     */
    public function deleteActivityData($data)
    {
        if (empty($data) && $data == false) {
            return [];
        }
        //删除
        $res = LifeFreeModel::getInstance()->deleteData(['id' => $data['id']]);
        return $res;
    }

    /**
     * 活动列表数据
     * @param $data
     * @return array
     */
    public function getActivityList($data)
    {
//        if (empty($data) && $data == false) {
//            return [];
//        }
        $page = !isset($data['page']) ? 1 : $data['page'];

        $pageSize = !isset($data['pageSize']) ? self::pageSize : $data['pageSize'];

        $condition = [];
        if (isset($data['name']) && !empty($data['name'])) {
            $condition[] = ['activity_name', 'LIKE', '%' . $data['name'] . '%'];
        }
        if (isset($data['status'])) {
            $condition[] = ['status', '=', $data['status']];
        }
        //列表--活动名称  创建时间 开奖方式  中奖次数/中奖人数  活动状态 下单引导  操作
        $list = LifeFreeModel::getInstance()->getPageList($condition, $page, $pageSize);
        if (!empty($list) && !empty($list['data'])) {
            foreach ($list['data'] as &$v) {
                //指定时间，指定数量处理
                $v->open_specify_time = $v->trigger_by_time == self::TYPE_ONE ? getFormatTime($v->open_specify_time) : '';
                $v->open_specify_num = $v->trigger_by_ticket == self::TYPE_ONE ? $v->open_specify_num : '';
                //中奖人数
                /**
                 *显示已购买的奖券的数量
                 */
                $v->buy_ticket_num = 0;
                /**
                 * 抽奖功能完成后更新
                 */
                $v->win_num = 0;
            }
        }
        return $list;
    }

    /**
     * 活动--抽奖记录
     * @param $data
     * @return array
     */
    public function getPrizeRecordList($data)
    {
        if (empty($data) && $data == false) {
            return [];
        }
        $page = !isset($data['page']) ? 1 : $data['page'];
        $pageSize = !isset($data['pageSize']) ? 5 : $data['pageSize'];

        $condition = [];
        $condition['activity_id'] = $data['id'];
        if (isset($data['name']) && !empty($data['name'])) {
            $condition[] = ['name', 'LIKE', '%' . $data['name'] . '%'];
        }
        if (isset($data['status'])) {
            $condition[] = ['status', '=', $data['status']];
        }
        if (isset($data['start_time']) && !empty($data['start_time'])) {
            $condition[] = ['create_time', '>=', strtotime($data['start_time'])];
        }
        if (isset($data['end_time']) && !empty($data['end_time'])) {
            $condition[] = ['create_time', '<=', strtotime($data['end_time'])];
        }

        //列表
        $field = ['members.uid', 'avatar', 'nickname', 'mobile', 'ticket_num', 'activity_lifefree_log.id', 'activity_lifefree_log.content', 'activity_lifefree_log.status'];
        $list = LifeFreeLogModel::getInstance()->left_join_listed($condition, $page, $pageSize, [], $field);
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                //需调用公共防范 访问头像地址
                $val->avatar = $val->avatar;
            }
        }
        return $list;
    }

    /**
     * 获取抽奖记录--奖券列表
     * @param $data
     * @return array
     */
    public function getRecordTicketList($data)
    {
        if (empty($data) && $data == false) {
            return [];
        }
        $page = !isset($data['page']) ? 1 : $data['page'];
        $pageSize = !isset($data['pageSize']) ? 5 : $data['pageSize'];

        $condition = [];
        $condition['log_id'] = $data['id'];

        //列表
//        $field = ['log_id','content','num','status','create_time'];
        $field = ['log_id', 'content', 'status', 'create_time'];
        $list = LifeFreeTicketModel::getInstance()->getPageList($condition, $page, $pageSize, $field);
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                $val->create_time = !empty($val->create_time) ? getFormatTime($val->create_time) : '';
            }
        }
        return $list;
    }

    /**
     * 活动详情
     * @param $data
     * @return array
     */
    public function getActivityInfo($data)
    {
        if (empty($data) && $data == false) {
            return [];
        }
        //详情
        $info = self::getActivityById($data['id'], ['*']);
        if (!empty($info)) {
            //时间戳处理
            $info->start_time = empty($info->start_time) ? '' : getFormatTime($info->start_time);
            $info->end_time = empty($info->start_time) ? '' : getFormatTime($info->end_time);
            $info->create_time = empty($info->start_time) ? '' : getFormatTime($info->create_time);
            $info->update_time = empty($info->start_time) ? '' : getFormatTime($info->update_time);
            //活动渠道处理
            //活动规则处理 --extra_rules 反序列化
        }
        return $info;
    }

    /**
     * 验证参数是否存在
     * @param $param
     * @param $data
     * @return bool
     */
    public static function paramExist($param, $data = [])
    {
        if (!empty($data) && isset($data[$param]) && !empty($data[$param])) {
            return true;
        } elseif (empty($data) && !empty($param)) {
            return true;
        }
        return false;
    }

    /**
     * 获取活动数据--通过id
     * @param $id
     * @param $field
     * @return array
     */
    public function getActivityById($id, $field = ['id'])
    {
        if (!empty($id)) {
            return LifeFreeModel::getInstance()->getInfo(['id' => $id], $field);
        }
        return [];
    }


    /**
     * 验证活动数据是否存在
     * @param $id
     * @return array
     */
    public function activityExists($id)
    {
        return empty($id) ? [] : self::getActivityById($id);
    }

    /**
     * 自由生活 开奖逻辑
     * @return int|void
     */
    public function goOpenDraw($activity_id)
    {
        //获取活动id
        $field = ['id', 'activity_name', 'ticket_num', 'trigger_by_ticket', 'open_specify_num', 'trigger_by_time', 'open_specify_time', 'trigger_method',
            'draw_prize_num', 'system_win_chance', 'user_win_chance', 'appoint_win', 'win_user', 'win_ticket'];
        $info = LifeFreeModel::getInstance()->getInfo(['id' => $activity_id], $field);
        if (empty($info)) {
            return $info;
        }
        $info_str = json_encode($info);
        $info = json_decode($info_str, true);
        $result = OpenPrizeServices::open_prize($info);
        if ($result['status'] == 0) {
            $open_local = $result['data']['open_local'];
            $sys_open_local = $result['data']['sys_open_local'];
            $open_local = array_merge($open_local, $sys_open_local);
            //更新中奖信息
            self::saveData($info, $open_local);
            //发送通知等
            return $open_local;
        }
        return false;
    }

    /**
     * 保存开奖结果
     * @return void
     */
    private function saveData($info, $open_local)
    {
        try {
            DB::beginTransaction();
            //第一步：处理活动信息 保存已开奖及中奖编号
            $data = ['status' => 2, 'win_num' => json_encode($open_local)];
            LifeFreeModel::getInstance()->updateSave(['id' => $info['id']], $data);

            //第二步：更新中奖券信息
            $ticketMode = LifeFreeTicketModel::getInstance();
            //：全部设置未中奖
            $data = ['status' => 1];
            $ticketMode->updateSave(['activity_id' => $info['id']], $data);
            //：设置中奖用户为已中奖
            $data = ['status' => 2];
            $ticketMode->updateSave(['activity_id' => $info['id']], $data, ['local_num' => $open_local]);

            //第三步：更新抽奖记录信息
            //:更新用户抽奖记录，获取中将用户的log_id 更新log表为中中奖状态
            $list = $ticketMode->getList(['activity_id' => $info['id']], ['id', 'uid', 'log_id', 'content'], ['local_num' => $open_local]);
            $new_list = [];
            if (!empty($list)) {
                foreach ($list as $val) {
                    $new_list[$val['log_id']][] = $val;
                }
            }
            //更新log记录
            foreach ($new_list as $val) {
                $content = [];
                foreach ($val as $v) {
                    $content[] = $v['content'];
                }
                $data = ['content' => self::arrayToString($content), 'status' => 1];
                $res = LifeFreeLogModel::getInstance()->updateSave(['log_id' => $info['id']], $data);
            }
            DB::commit();
            return array('state' => 200, 'msg' => 'success');
        } catch (Exception $e) {
            DB::rollback();
            return array('state' => false, 'msg' => $e->getMessage());
        }

    }


}
